package com.by.controller;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import com.by.authorinterceptor.ProductValidator;
import com.by.bean.ProductImage;
import com.by.config.SystemConfig;
import com.by.config.SystemConfig.PointType;
import com.by.model.Brand;
import com.by.model.Product;
import com.by.model.Product.WeightUnit;
import com.by.model.ProductAttribute;
import com.by.model.ProductAttribute.AttributeType;
import com.by.model.ProductCategory;
import com.by.model.ProductType;
import com.by.server.ProductImageService;
import com.by.util.SerialNumberUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;






public class ProductController extends BaseAdminController<Product> {
	private List<UploadFile> productImages;
	
	
	private Product product;
	
	Map<String, String> productAttributeMap = new HashMap<String, String>();
	
	public void list(){
		findByPage();
		render("/admin/product_list.html");
	}
	// 添加
	public void add() {
			setAttr("productCategoryTreeList", getProductCategoryTreeList());
			setAttr("allBrand", getAllBrand());
			setAttr("allWeightUnit", getAllWeightUnit());
			setAttr("allProductType", getAllProductType());
			render("/admin/product_input.html");
	}
	
	// 保存
		@Before(ProductValidator.class)
		public void save() {
			productImages = getFiles();
			product = getModel(Product.class);
			String weightUnit = getPara("weightUnit","");
			
			if (StrKit.notBlank(weightUnit)){
				product.set("weightUnit", WeightUnit.valueOf(weightUnit).ordinal());
			}		
			if (product.getBigDecimal("price").compareTo(new BigDecimal("0")) < 0) {
				addActionError("销售价不允许小于0");
				return;
			}		
			if (product.getBigDecimal("marketPrice").compareTo(new BigDecimal("0")) < 0) {
				addActionError("市场价不允许小于0");
				return;
			}		
			if (product.getDouble("weight") < 0) {
				addActionError("商品重量只允许为正数或零!");
				return;
			}		
			if (StringUtils.isNotEmpty(product.getStr("productSn"))) {
				if (Product.dao.isExist(product.getStr("productSn"))) {
					addActionError("货号重复,请重新输入!");
					return;
				}
			} else {
				String productSn = SerialNumberUtil.buildProductSn();
				product.set("productSn",productSn);
			}		
				
			if (getSystemConfig().getPointType() == PointType.productSet) {
				if (product.get("point") == null) {
					addActionError("积分不允许为空!");
					return;
				}
			} else {
				product.set("point",0);
			}
			
			// 处理上传的图片
			if (productImages != null && productImages.size() > 0) {
				String allowedUploadImageExtension = getSystemConfig().getAllowedUploadImageExtension().toLowerCase();
				if (StringUtils.isEmpty(allowedUploadImageExtension)) {
					addActionError("不允许上传图片文件!");
					return;
				}
				for(int i = 0; i < productImages.size(); i ++) {
					File images = productImages.get(i).getFile();
					String productImageExtension =  StringUtils.substringAfterLast(images.getName(), ".").toLowerCase();
					String[] imageExtensionArray = allowedUploadImageExtension.split(SystemConfig.EXTENSION_SEPARATOR);
					if (!ArrayUtils.contains(imageExtensionArray, productImageExtension)) {
						addActionError("只允许上传图片文件类型: " + allowedUploadImageExtension + "!");
						return;
					}
					if (getSystemConfig().getUploadLimit() != 0 && images.length() > getSystemConfig().getUploadLimit() * 1024) {
						addActionError("此上传文件大小超出限制!");
						return;
					}
				}
			}
					
			List<ProductImage> productImageList = new ArrayList<ProductImage>();
			if (productImages != null && productImages.size() > 0) {
				for(int i = 0; i < productImages.size(); i ++) {
					ProductImage productImage = ProductImageService.service.buildProductImage(productImages.get(i).getFile());
					productImageList.add(productImage);
				}
			}		
			product.setProductImageList(productImageList);
			product.set("freezeStore",0);
			
			if (StrKit.notBlank(product.getStr("productType_id"))) {			
				List<ProductAttribute> enabledProductAttributeList = ProductAttribute.dao.getEnabledProductAttributeList(product.getStr("productType_id"));
				for (ProductAttribute productAttribute : enabledProductAttributeList) {
					String parameterValues = getPara(productAttribute.getStr("id"));				
					if (productAttribute.getBoolean("isRequired") && (parameterValues == null || parameterValues.isEmpty())) {
						addActionError(productAttribute.getStr("name") + "不允许为空!");
						return;
					}				
					AttributeType attributeType = ProductAttribute.dao.findById(productAttribute.getStr("id")).getAttributeType();				
					if (StrKit.notBlank(parameterValues)) {
						if (attributeType == AttributeType.number) {
							Pattern pattern = Pattern.compile("^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)(?:\\.\\d+)?");
							Matcher matcher = pattern.matcher(parameterValues);
							if (!matcher.matches()) {
								addActionError(productAttribute.getStr("name") + "只允许输入数字!");
								return;
							}
						}
						if (attributeType == AttributeType.alphaint) {
							Pattern pattern = Pattern.compile("[a-zA-Z]+");
							Matcher matcher = pattern.matcher(parameterValues);
							if (!matcher.matches()) {
								addActionError(productAttribute.getStr("name") + "只允许输入字母!");
								return;
							}
						}
						if (attributeType == AttributeType.date) {
							Pattern pattern = Pattern.compile("\\d{4}[\\/-]\\d{1,2}[\\/-]\\d{1,2}");
							Matcher matcher = pattern.matcher(parameterValues);
							if (!matcher.matches()) {
								addActionError(productAttribute.getStr("name") + "日期格式错误!");
								return;
							}
						}
						if (attributeType == AttributeType.select || attributeType == AttributeType.checkbox) {
							List<String> attributeOptionList = productAttribute.getAttributeOptionList();
							if (!attributeOptionList.contains(parameterValues)) {
								addActionError("参数错误!");
								return;
							}
						}
						productAttributeMap.put(productAttribute.getStr("id"), parameterValues);
					}
				}
			} 		
			product.save(product);	}	
	// 获取所有商品类型
     public List<ProductType> getAllProductType() {
			return ProductType.dao.getAll();
	}
	// 获取所有重量单位
	public List<WeightUnit> getAllWeightUnit() {
		   List<WeightUnit> allWeightUnit = new ArrayList<WeightUnit>();
			for (WeightUnit weightUnit : WeightUnit.values()) {
				allWeightUnit.add(weightUnit);
			}
			return allWeightUnit;
	}
		// 获取所有品牌
	public List<Brand> getAllBrand() {
	    	return Brand.dao.getAll();
	}
	// 获取商品分类树
	public List<ProductCategory> getProductCategoryTreeList() {
		  return ProductCategory.dao.getProductCategoryTreeList();
	}
}
